<template>
  <div class="layout-container">
    <!-- 固定侧边栏 -->
    <div class="sidebar">
      <div class="logo">
        <h2>美发会员管理系统</h2>
      </div>

      <el-menu
        :default-active="$route.path"
        class="sidebar-menu"
        router
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
      >
        <menu-item
          v-for="menu in userMenus"
          :key="menu.id"
          :menu="menu"
        />
      </el-menu>
    </div>

    <!-- 主内容区 -->
    <div class="main-container">
      <!-- 顶部导航 -->
      <div class="header">
        <div class="header-left">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item v-if="$route.meta.title">{{ $route.meta.title }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div class="header-right">
          <!-- 通知中心 -->
          <notification-center class="notification-center" />

          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-avatar
                :size="30"
                :src="userStore.currentUser.avatar"
                class="user-avatar-header"
              >
                <el-icon><Avatar /></el-icon>
              </el-avatar>
              {{ userStore.currentUser.name || userStore.currentUser.username }}
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="main-content">
        <router-view />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserInfo } from '../api/auth'
import MenuItem from '../components/MenuItem.vue'
import NotificationCenter from '../components/NotificationCenter.vue'
import { setUserPermissions, clearPermissions, usePermissions, setRefreshCallback } from '../stores/permission'
import { useUserStore } from '../stores/user'
import { isTokenExpired } from '../utils/tokenUtils'
import { addDynamicRoutes, clearDynamicRoutes } from '../router/index'

const router = useRouter()
const userStore = useUserStore()
const { userInfo, userMenus, userButtons } = usePermissions()

// 获取用户信息和权限
const fetchUserInfo = async () => {
  try {
    const response = await getUserInfo()
    
    // 更新用户 Store
    userStore.setCurrentUser(response.data)
    
    // 使用响应式权限状态
    setUserPermissions(
      response.data.buttons || [],
      response.data.menus || [],
      response.data
    )
    
    // 添加动态路由
    if (response.data.menus && response.data.menus.length > 0) {
      addDynamicRoutes(response.data.menus)
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 处理下拉菜单命令
const handleCommand = async (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'logout':
      try {
        await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        userStore.logout()
        clearPermissions()
        clearDynamicRoutes()
        ElMessage.success('退出登录成功')
        router.push('/login')
      } catch (error) {
        // 用户取消操作
      }
      break
  }
}

// 刷新用户权限（供其他组件调用）
const refreshUserPermissions = async () => {
  await fetchUserInfo()
}

onMounted(async () => {
  // 检查权限是否已经加载
  const { userMenus } = usePermissions()
  
  // 只有在权限数据为空时才从服务器获取
  if (!userMenus.value || userMenus.value.length === 0) {
    console.log('Layout: 权限数据为空，从服务器获取')
    try {
      await fetchUserInfo()
    } catch (error) {
      console.error('Layout: 获取用户信息失败:', error)
      // 如果获取用户信息失败，让axios拦截器处理token刷新或跳转登录
    }
  } else {
    console.log('Layout: 权限数据已存在，跳过加载')
  }

  // 设置刷新回调
  setRefreshCallback(refreshUserPermissions)
})
</script>

<style scoped>
.layout-container {
  height: 100vh;
}

.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  width: 250px;
  height: 100vh;
  background-color: #304156;
  overflow: hidden;
  z-index: 1000;
}

.logo {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2b3a4b;
  color: white;
  border-bottom: 1px solid #1f2d3d;
}

.logo h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.sidebar-menu {
  border: none;
  height: calc(100vh - 60px);
  overflow-y: auto;
}

.main-container {
  margin-left: 250px;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  background: white;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
  flex-shrink: 0;
}

.header-left {
  flex: 1;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.notification-center {
  margin-right: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f5f5;
}

.user-info .el-icon {
  margin: 0 4px;
}

.user-avatar-header {
  margin-right: 8px;
  border: 1px solid #e6e6e6;
}

.main-content {
  background-color: #f0f2f5;
  padding: 20px;
  overflow-y: auto;
  flex: 1;
  height: calc(100vh - 60px);
}

:deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
}

:deep(.el-submenu .el-submenu__title) {
  height: 50px;
  line-height: 50px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    transform: translateX(-100%);
    transition: transform 0.3s ease;
  }

  .main-container {
    margin-left: 0;
  }

  /* 可以添加一个切换按钮来显示/隐藏侧边栏 */
  .sidebar.mobile-show {
    transform: translateX(0);
  }
}
</style> 